import { http } from './http';
const SymbolId = Symbol('id');
const SymbolHttp = Symbol('http');
export default class Api {
	constructor() {
		this.initSimpleInstance = key => {
			return this.initSingle(key, {
				baseURL: `/api/${key}`
			});
		};
		this.initInstance = (key, config, callback) => {
			return this.initSingle(key, config, callback);
		};
		this.destroy = () => this.http.destroy(this.id);
		this.request = config => {
			const tmp = {
				id: this.id,
				...config
			};
			return this.http.request(tmp);
		};
		this.all = configs =>
			new Promise((resolve, reject) => {
				this.http
					.raw()
					.all(configs.map(config => this.request(config)))
					.then(
						this.http.raw().spread((...results) => {
							resolve(results);
						})
					)
					.catch(error => {
						reject(error);
					});
			});
		this.allMethod = ApiMethods =>
			new Promise((resolve, reject) => {
				this.http
					.raw()
					.all(ApiMethods)
					.then(
						this.http.raw().spread((...results) => {
							resolve(results);
						})
					)
					.catch(error => {
						reject(error);
					});
			});
		this[SymbolHttp] = http;
		this.method = http.method;
	}
	/**
	 * @author 戴俊明 <idaijunming@163.com>
	 * @description 初始化通用http请求配置，如果已被初始化，覆盖原有配置。该方法返回的实例可做链式调用。
	 * @date 2020/1/30 20:50
	 **/
	init(config, callback) {
		this[SymbolId] = this.http.create(
			{
				id: Symbol.for('Api'),
				...config
			},
			callback
		);
		return this;
	}
	/**
	 * @author 戴俊明 <idaijunming@163.com>
	 * @description 根据key初始化http请求配置，如果已被初始化，覆盖原有配置。该方法返回的实例可做链式调用。
	 * @date 2020/1/30 20:53
	 **/
	initSingle(key, config, callback) {
		this[SymbolId] = this.http.create(
			{
				id: Symbol.for(key),
				...config
			},
			callback
		);
		return this;
	}
	get id() {
		return this[SymbolId];
	}
	get http() {
		return this[SymbolHttp];
	}
}
